package ast.decl;

import icg.Quadruple;

import java.util.Vector;

import ts.FunInfo;
import ts.Info;
import ts.SymbolTable;
import ast.Node;
import ast.stmt.Statement;
import ast.type.Type;

public class ProDecl extends Declaration {
	private Integer id;
	private Type type;
	private Vector<Declaration> listPar;
	private Vector<Declaration> listVar;
	private Statement seq;

	public void typeCheck() {
		Info info = Node.st.getInfo(id);
		info.setType(type);
		FunInfo fi = (FunInfo) info;
		fi.setListPar(listPar);

		for (int i = 0; i < listPar.size(); i++) {
			listPar.elementAt(i).typeCheck();
		}
		for (int i = 0; i < listVar.size(); i++)
			listVar.elementAt(i).typeCheck();
		seq.typeCheck(type);
		if (type != Type.VOID && !seq.isReturned()) {
			SymbolTable.errors++;
			System.out.println("not all paths return in proc");
		}
		if (type == Type.VOID && seq.isReturned()) {
			System.out.println("return command must be only in a function");
			SymbolTable.errors++;
		}
		if (seq.hasCtrlFlow()) {
			SymbolTable.errors++;
			System.out
					.println("statement of control flow must be in a repetition statement");
		}
	}

	public ProDecl(Integer id, Type type, Vector<Declaration> listPar,
			Vector<Declaration> listVar) {
		this.id = id;
		this.type = type;
		this.listPar = listPar;
		this.listVar = listVar;
	}

	public void setSeq(Statement seq) {
		this.seq = seq;
	}

	public Statement getSeq() {
		return seq;
	}

	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < listPar.size(); i++)
			sb.append(listPar.elementAt(i).toString()).append("\n");
		String par = sb.toString();
		sb = new StringBuffer();
		for (int i = 0; i < listVar.size(); i++)
			sb.append(listVar.elementAt(i).toString()).append("\n");
		String var = sb.toString();
		return "<ProDecl id=\"" + id + "\" type=\"" + type + "\">"
				+ "\n<ParList>\n" + par + "</ParList>" + "\n<VarList>\n" + var
				+ "\n</VarList>" + "\n<SeqStmt>\n" + seq.toString()
				+ "\n</SeqStmt>" + "\n</ProDecl>";
	}

	@Override
	public void genCode() {
		Node.icg.newQuadrupleTable(id);
		for (Declaration d : listPar)
			d.genCode();
		for (Declaration d : listVar)
			d.genCode();
		seq.genCode();
		if (type == Type.VOID)
			Node.icg.gen(Quadruple.retorno());
	}

}
